import React, { useEffect, useState, useRef } from 'react';
import { Table, Form, Select, Button, Typography, Flex } from 'antd';
import { SearchOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { download, getUserName, transformArray } from '../../../utils/commonUtil';
import { APPROVAL_STATUS } from '../../../utils/constant';
import './index.scss';
import RadarChart from './Components/RadarChart';
import ChartZoomModal from './Components/ChartZoomModal';
import { apiSynTouchSummaryFilter, apiSynTouchSummaryList, apiSynTouchSummaryDrawRadar, apiSynTouchSummaryDownload } from '../../../services/synTouch/summary';


const { Title } = Typography;
const SynTouchSummaryData = () => {
  const { APPROVED } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const radarChartRef = useRef(null);
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [synTouchFileNameList, setSynTouchFileNameList] = useState([]);
  const [buTypeList, setBuTypeList] = useState([]);
  const [productList, setProductList] = useState([]);
  const [materialList, setMaterialList] = useState([]);
  const [projectList, setProjectList] = useState([]);
  const [statusList, setStatus] = useState([]);
  const [chartsData, setChartsData] = useState();
  const [chartsZoomModalVisable, setChartsZoomModalVisable] = useState(false);

  const columns = [
    {
      title: t('synTouch.percept'),
      dataIndex: 'percepts',
      align: 'center'
    },
    {
      title: t('synTouch.material'),
      dataIndex: 'material',
      align: 'center'
    },
    {
      title: t('synTouch.mean'),
      dataIndex: 'mean',
      align: 'center'
    },
    {
      title: t('synTouch.sd'),
      dataIndex: 'sd',
      align: 'center'
    },
    {
      title: t('synTouch.n'),
      dataIndex: 'number',
      align: 'center'
    },
  ];
  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes || [],
      projectNames: formData?.projectNames || [],
      productNames: formData?.productNames || [],
      synTouchFileNames: formData?.synTouchFileNames || [],
      materials: formData?.materials || [],
      requestStatus: formData?.requestStatus || [],
    };
    return params;
  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
    apiSynTouchSummaryDrawRadarAsync();
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    console.log(params);
    apiSynTouchSummaryList(params).then((res) => {
      if (res?.data?.code === 200) {
        setDataList(res?.data?.data?.items);
        setTotalPage(res?.data?.data?.total);
      };
    });
  };

  // 调用下拉框api
  const apiSelectAsync = async () => {
    apiSynTouchSummaryFilter().then((res) => {
      if (res?.data?.code === 200) {
        setSynTouchFileNameList(transformArray(res?.data?.data?.synTouchFileName));
        setMaterialList(transformArray(res?.data?.data?.material));
        setProjectList(transformArray(res?.data?.data?.projectName));
        setBuTypeList(transformArray(res?.data?.data?.buType));
        setProductList(transformArray(res?.data?.data?.productName));
        setStatus(transformArray(res?.data?.data?.requestStatus));
      }
    });
  };

  const downloadHandle = async () => {
    const imgFile = await radarChartRef?.current?.chartsExportImg();
    console.log(imgFile);
    if (imgFile) {
      let param = new FormData();
      param.append('file', imgFile);
      getQueryParams()?.buTypes?.length > 0 && param.append('buTypes', getQueryParams()?.buTypes);
      getQueryParams()?.materials?.length > 0 && param.append('materials', getQueryParams()?.materials);
      getQueryParams()?.projectNames?.length > 0 && param.append('projectNames', getQueryParams()?.projectNames);
      getQueryParams()?.productNames?.length > 0 && param.append('productNames', getQueryParams()?.productNames);
      getQueryParams()?.synTouchFileNames?.length > 0 && param.append('synTouchFileNames', getQueryParams()?.synTouchFileNames);
      param.append('userId', getUserName());
      apiSynTouchSummaryDownload(param).then((res) => {
        if (res?.data) {
          download(res)
        }
      })
    }
  };
  // 雷达图接口
  const apiSynTouchSummaryDrawRadarAsync = async () => {
    const params = getQueryParams();
    const { data } = await apiSynTouchSummaryDrawRadar(params);
    setChartsData(data?.data?.items);
  };
  const zoomHandle = (ratio) => {
    setChartsZoomModalVisable(true);
  };
  useEffect(() => {
    // 正式数据
    apiSynTouchSummaryDrawRadarAsync();
    queryList();
    // 调用下拉框api
    apiSelectAsync();
  }, [])

  return (
    <div className='syn-touch-summary-wrap'>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('synTouch.synTouchSummaryData')}</Title>
          <Button onClick={() => { downloadHandle() }}>{t('common.download')}</Button>
        </Flex>
      </div>

      <div className='page-content-wrap'>
        <div className='box-wrap'>
          <Form form={form} className='filter-wrap'>
            <Flex align='center' gap="middle">
              <Form.Item name="buTypes"
                label={t('common.buType')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buTypeList} />
              </Form.Item>
              <Form.Item name="projectNames"
                label={t('common.project')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={projectList} />
              </Form.Item>
              <Form.Item name="productNames"
                label={t('common.product')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={productList} />
              </Form.Item>
              <Form.Item name="synTouchFileNames"
                label={t('common.sheetName')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={synTouchFileNameList} />
              </Form.Item>
              <Form.Item name="materials"
                label={t('common.codes')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={materialList} />
              </Form.Item>
              <Form.Item name="requestStatus"
                initialValue={[APPROVED]}
                label={t('common.status')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
                <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={statusList} />
              </Form.Item>
              <Button
                className='search-btn'
                type="primary"
                onClick={serach}
                icon={<SearchOutlined style={{ fontSize: 20 }} />}
              />
            </Flex>
          </Form>
        </div>
        <Flex justify='space-between'>
          <div className='box-wrap' style={{ width: '50%', marginRight: '12px' }}>
            <Flex justify='space-between' align='center'>
              <div className='title'>{t('common.plot')}</div>
              <div>
                <Button type="text" onClick={() => { zoomHandle() }} icon={<ZoomInOutlined style={{ fontSize: 20 }} />} />
                <Button type="text" onClick={() => { zoomHandle() }} icon={<ZoomOutOutlined style={{ fontSize: 20 }} />} />
              </div>
            </Flex>
            {
              chartsData &&
              <div id='radar-chart-wrap'>
                <div style={{ width: '100%', height: '400px', }}>
                  <RadarChart chartsData={chartsData} ref={radarChartRef} type='list' />
                </div>
              </div>
            }
          </div>
          <div className='box-wrap' style={{ width: '50%' }}>
            <div className='title'>{t('common.summary')}</div>
            <Table
              columns={columns}
              dataSource={dataList}
              size="small"
              pagination={{
                total: totalPage,
                current: currentPage,
                pageSize: pageSize,
                onChange: (_crrentPage, _pageSize) => {
                  setCurrentPage(_crrentPage);
                  setPageSize(_pageSize);
                  queryList(_crrentPage, _pageSize);
                },
                pageSizeOptions: [10, 20, 50],
                showSizeChanger: true,
                showTotal: (total) => {
                  return `Total ${total} items`;
                },
              }}
            />
          </div>
        </Flex>
      </div>
      {
        chartsZoomModalVisable &&
        <ChartZoomModal
          chartsZoomModalVisable={chartsZoomModalVisable}
          setChartsZoomModalVisable={setChartsZoomModalVisable}
          // zoomRatio={zoomRatio}
          // setZoomRatio={setZoomRatio}
          chartsData={chartsData}
        />
      }
    </div>
  )
};

export default SynTouchSummaryData;
